import React, { useMemo } from 'react';
import { Redirect, useLocation } from 'react-router';

import { flattenTree } from '../utils/common';
import { publicPages } from '../lib/config';
import { useAuth } from '../store/modules/auth';

// 鉴权wrapper
const Authorization = ({ children }) => {
  const { menuList } = useAuth();
  const location = useLocation();
  const authPermission = useMemo(
    () => flattenTree(menuList).map((item) => item.url),
    [menuList],
  );

  const hasPermission = useMemo(() => {
    return authPermission.includes(location.pathname);
  }, [location.pathname, authPermission]);

  if (!hasPermission && !publicPages.includes(location.pathname)) {
    return <Redirect to="/403" />;
  }
  return <>{children}</>;
};

export default Authorization;
